package app.server.project.main.service.service;

import app.server.project.core.constants.Def;
import app.server.project.main.service.db.dao.DeviceBaseDao;
import app.server.project.main.service.db.dao.UserDeviceDao;
import app.server.project.main.service.db.entity.UserDeviceEntity;
import app.server.project.main.service.dto.device.ChangeDevRoomReq;
import app.server.project.main.service.dto.device.DeviceDto;
import cn.hutool.core.util.IdUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@AllArgsConstructor
@Service
public class UserDeviceService {

    private UserDeviceDao userDeviceDao;
    private DeviceBaseDao deviceBaseDao;

    public List<DeviceDto> getAllDevice(long userId){
        var data=this.userDeviceDao.getData(userId);
        return data.stream().map(v->{
            var base=this.deviceBaseDao.getDataById(v.getDeviceId());
            return DeviceDto.of(v.getDeviceId(), Objects.isNull(base)?Def.Zero: base.getDeviceTypeId());
        }).toList();
    }

    public void bindDevice(long userId,long deviceId){
        //检查是否已经绑定
        var data=this.userDeviceDao.getData(userId);
        if (data.stream().anyMatch(v->{
            return v.getUserId()==deviceId;
        })){
            return;
        }
        data.add(UserDeviceEntity.of(IdUtil.getSnowflakeNextId(),userId,deviceId, Def.Zero));
    }

    public void unBind(long userId,long deviceId){
        //检查是否已经绑定
        var data=this.userDeviceDao.getData(userId);
        data.removeIf(v->{
            if (v.getDeviceId()==deviceId){
                v.setIsDel(Def.True);
                return true;
            }
            return false;
        });
    }



    public void changeRoomId(ChangeDevRoomReq req,long userId){
        //检查是否已经绑定
        var data=this.userDeviceDao.getData(userId);
        data.forEach(v->{
            if (v.getDeviceId()==req.getDevId()){
                v.setRoomId(req.getRoomId());
            }
        });
    }
}
